﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
public partial class User_Controls_MathCaptcha : System.Web.UI.UserControl
{
    public bool Success = false;
    protected void Page_Load(object sender, EventArgs e)
    {
        // if the page is first requested  and not postback, we need to initialize our numbers:
        if (!IsPostBack)
        {
            System.Random rand = new Random((int)DateTime.Now.Ticks);
            int num1 = rand.Next(1, 10);
            int num2 = rand.Next(1, 10);
            int total = num1 + num2;
            Session["total"] = total;
            lblNum1.Text = num1.ToString();
            lblNum2.Text = num2.ToString();
        }
        else
        {
            Success = Validate();
        }
    }
    public bool Validate()
    {
        // 1. First, make sure user entered a number in the sum textbox:
        // all these labels are optional, you can just handle the public Success field being True|False
        int sum = 0;        
        if (!int.TryParse(txtSum.Text, out sum))
        {
            Label2.Visible = false;
            Label2.Text = "Need to put a sum in the textbox, Captain.";
            Label2.ForeColor = System.Drawing.Color.Red;
            return false;
        }
        // 2. Compare their entry with the stored sum of the two numbers:
        if (sum != (int)Session["total"])
        {
            // They got it wrong...
            Label2.Visible = false;
            Label2.ForeColor = System.Drawing.Color.Red;
            Label2.Text = "InCorrect Answer.... Please try again.";
            return false;
        }
        else
        {
            // They got it right:
            Label2.Visible = false;
            Label2.ForeColor = System.Drawing.Color.LightGreen;
            Label2.Text = "Success!";
            return true;
        }
    }
}